package cn.easyplatform.studio.web.editors.project;

import cn.easyplatform.entities.EntityInfo;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.link.GetLinkCmd;
import cn.easyplatform.studio.cmd.taskLink.PagingTaskLinkCmd;
import cn.easyplatform.studio.cmd.version.GetEntryListCmd;
import cn.easyplatform.studio.utils.StudioUtil;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.LinkVo;
import cn.easyplatform.studio.vos.QueryTypeLinkVo;
import cn.easyplatform.studio.vos.TypeLinkVo;
import cn.easyplatform.studio.web.editors.ComponentCallback;
import cn.easyplatform.studio.web.layout.WorkbenchController;
import cn.easyplatform.studio.web.views.impl.AbstractView;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.*;
import org.zkoss.zul.event.PagingEvent;
import org.zkoss.zul.event.ZulEvents;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class RootTaskExportEditor extends DictExportEditor {

    protected Listbox sources;

    private QueryTypeLinkVo result;
    private List<TypeLinkVo> selectedVos = new ArrayList<>();
    public RootTaskExportEditor(WorkbenchController workbench, String id) {
        super(workbench, id);
    }

    @Override
    protected void dispatch(Event evt) {
        if (evt.getTarget() == showPaging) {// 分页
            PagingEvent pe = (PagingEvent) evt;
            int pageNo = pe.getActivePage() + 1;
            result = StudioApp.execute(showPaging,
                    new PagingTaskLinkCmd("*", null, showPaging.getPageSize(), pageNo));
            redrawList(result.getLinkVoList(), false, "");
        } else if (evt.getTarget() instanceof Listitem) {
            /*if (Events.ON_OPEN.equals(evt.getName())) {
                Treeitem item = (Treeitem) evt.getTarget();
                TypeLinkVo vo = item.getValue();
                result = StudioApp.execute(item, new RootTaskLinkCmd(result, vo));
                redrawList(result.getLinkVoList(), false, vo.getEntityId());
            } else */if (evt.getName().equals((Events.ON_DOUBLE_CLICK))) {
                Listitem ti = (Listitem) evt.getTarget();
                TypeLinkVo vo= ti.getValue();
                AbstractView.createRootTaskView(new ComponentCallback(this.id, Labels.getLabel("entity.link.detail.title")),
                        vo.getEntityId()).doOverlapped();
            } else if (evt.getName().equals((Events.ON_CLICK))) {
                Set<Listitem> treeItems = sources.getSelectedItems();
                selectedVos = new ArrayList<>();
                for (Listitem treeitem : treeItems) {
                    selectedVos.add((TypeLinkVo) treeitem.getValue());
                }
            }
        } else if (evt.getName().equals(Events.ON_CLICK)) {
            Component comp = evt.getTarget();
            if (comp.getId().equals("rootTaskExport_button_query")) {
                StringBuffer valueStr = new StringBuffer(Strings.isBlank(id.getValue()) == false ? id.getValue().trim():" ").append(",");
                valueStr.append(Strings.isBlank(name.getValue()) == false ? name.getValue().trim():" ").append(",");
                valueStr.append(Strings.isBlank(desp.getValue()) == false ? desp.getValue().trim():" ");
                result = StudioApp.execute(showPaging,
                        new PagingTaskLinkCmd("entityId,entityName,entityDesp", valueStr.toString(), showPaging.getPageSize(), 1));
                if (Double.valueOf(result.getTotalSize()) / Double.valueOf(showPaging.getPageSize()) <= 1.0)
                    showPaging.setVisible(false);
                else {
                    showPaging.setVisible(true);
                    showPaging.setActivePage(0);
                    showPaging.setTotalSize(result.getTotalSize());
                }
                allListCheck.setChecked(false);
                pageListCheck.setChecked(false);
                revListCheck.setChecked(false);
                checkPage = -1;
                redrawList(result.getLinkVoList(), false, "");
            } else if (comp.getId().equals("rootTaskExport_image_chooseAllBtn")) {
                select(false);
            } else if (comp.getId().equals("rootTaskExport_image_chooseBtn")) {
                select(true);
            } else if (comp.getId().equals("rootTaskExport_image_removeBtn")) {
                unselect(true);
            } else if (comp.getId().equals("rootTaskExport_image_removeAllBtn")) {
                unselect(false);
            } else if (comp.getId().equals("rootTaskExport_toolbarbutton_export")) {
                export(comp);
            }
        } else if (evt.getName().equals(Events.ON_CHECK)) {
            Checkbox r = (Checkbox) evt.getTarget();
            doCheck(r);
        }
    }

    @Override
    public void create(Object... args) {
        Idspace is = createPanel(Labels.getLabel("menu.repo.export.main.entity"), "~./images/action.gif",
                "~./include/editor/project/rootTaskExport.zul");
        id = (Textbox)is.getFellow("rootTaskExport_textbox_id");
        desp = (Textbox)is.getFellow("rootTaskExport_textbox_desp");
        name = (Textbox)is.getFellow("rootTaskExport_textbox_name");
        sources = (Listbox)is.getFellow("rootTaskExport_listbox_sources");
        targets = (Listbox)is.getFellow("rootTaskExport_listbox_targets");
        comment = (Textbox) is.getFellow("rootTaskExport_textbox_comment");
        showPaging = (Paging) is.getFellow("rootTaskExport_paging_showPaging");
        Button searchBtn = (Button)is.getFellow("rootTaskExport_button_query");
        searchBtn.addEventListener(Events.ON_CLICK, this);
        allListCheck = (Checkbox)is.getFellow("rootTaskExport_checkbox_checkAll");
        allListCheck.addEventListener(Events.ON_CHECK, this);
        pageListCheck = (Checkbox)is.getFellow("rootTaskExport_checkbox_checkPage");
        pageListCheck.addEventListener(Events.ON_CHECK, this);
        revListCheck = (Checkbox)is.getFellow("rootTaskExport_checkbox_checkRev");
        revListCheck.addEventListener(Events.ON_CHECK, this);
        is.getFellow("rootTaskExport_image_chooseAllBtn").addEventListener(Events.ON_CLICK, this);
        is.getFellow("rootTaskExport_image_chooseBtn").addEventListener(Events.ON_CLICK, this);
        is.getFellow("rootTaskExport_image_removeBtn").addEventListener(Events.ON_CLICK, this);
        is.getFellow("rootTaskExport_image_removeAllBtn").addEventListener(Events.ON_CLICK, this);
        is.getFellow("rootTaskExport_toolbarbutton_export").addEventListener(Events.ON_CLICK, this);
        redraw();
    }

    private void redraw() {
        result = StudioApp.execute(new PagingTaskLinkCmd("*", null, showPaging.getPageSize(),1));
        if (Double.valueOf(result.getTotalSize()) / Double.valueOf(showPaging.getPageSize()) <= 1.0)
            showPaging.setVisible(false);
        else {
            showPaging.setVisible(true);
            showPaging.setTotalSize(result.getTotalSize());
            showPaging.addEventListener(ZulEvents.ON_PAGING, this);
        }
        redrawList(result.getLinkVoList(), true, "");
    }

    private void redrawList(List<TypeLinkVo> list, boolean isInit, String rootTypeLinkId) {
        sources.getItems().clear();
        List<String> children = new ArrayList<>();
        children.add(rootTypeLinkId);
        allTreeChildren(list);
    }

    private void allTreeChildren(List<TypeLinkVo> list) {
        for (TypeLinkVo vo : list) {
            if (LinkVo.ENTITYSTATUS.equals(vo.getStatus()) && vo.ROOTENTITYID.equals(vo.isRoot())) {
                Listitem item = new Listitem();
                item.setValue(vo);
                item.appendChild(new Listcell(vo.getEntityId()));
                item.appendChild(new Listcell(vo.getEntityName()));
                item.appendChild(new Listcell(vo.getEntityDesp()));
                item.appendChild(new Listcell(
                        StudioUtil.getSringWithEntityType(vo.getEntityType(), vo.getEntitySubType())));
                item.appendChild(new Listcell(vo.getUpdateDate() == null ? null: vo.getUpdateDate().toString()));
                item.appendChild(new Listcell(vo.getUpdateUser()));
                item.addEventListener(Events.ON_CLICK, this);

                List<String> selectedEntityId = new ArrayList<>();
                for (TypeLinkVo linkVo : selectedVos) {
                    selectedEntityId.add(linkVo.getEntityId());
                }
                if (selectedEntityId.contains(vo.getEntityId()))
                    item.setSelected(true);
                else
                    item.setSelected(false);
                item.addEventListener(Events.ON_DOUBLE_CLICK, this);
                sources.getItems().add(item);
            }
        }
    }

    private void select(boolean selectFlag) {
        for (Listitem sel : sources.getItems()) {
            if (selectFlag && !sel.isSelected())
                continue;
            if (sel.getValue() != null) {
                boolean exists = false;
                TypeLinkVo s = sel.getValue();
                for (Listitem li : targets.getItems()) {
                    TypeLinkVo t = li.getValue();
                    if (s.getEntityId().equals(t.getEntityId())) {
                        exists = true;
                        break;
                    }
                }
                if (!exists) {
                    Listitem li = new Listitem();
                    li.appendChild(new Listcell(s.getEntityId()));
                    li.appendChild(new Listcell(s.getEntityName()));
                    li.appendChild(new Listcell(s.getEntityDesp()));
                    li.appendChild(new Listcell(s.getEntityType()));
                    li.appendChild(new Listcell(s.getUpdateDate() == null? null: s.getUpdateDate().toString()));
                    li.appendChild(new Listcell(s.getUpdateUser()));
                    li.setValue(s);
                    targets.appendChild(li);
                }
            }
        }
    }

    private void unselect(boolean selectedFlag) {
        if (selectedFlag) {
            if (targets.getSelectedCount() > 0) {
                List<Listitem> items = new ArrayList<Listitem>();
                for (Listitem li : targets.getSelectedItems())
                    items.add(li);
                for (Listitem li : items)
                    li.detach();
            }
        } else
            targets.getItems().clear();
    }

    protected void doCheck(Checkbox cbx) {
        if (cbx.getValue().equals("1") || cbx.getValue().equals("3")) {
            Iterator<Component> itr = sources.queryAll("treeitem").iterator();
            while (itr.hasNext()) {
                Treeitem ti = (Treeitem) itr.next();
                if (ti.getValue() != null) {

                    if (cbx.getValue().equals("1")) {
                        ti.setSelected(cbx.isChecked());
                        if (cbx.isChecked())
                            checkItem = CheckItem.SelectedAllItem;
                        else
                            checkItem = checkItem.UnSelectedAllItem;
                    }
                    else {
                        ti.setSelected(!ti.isSelected());
                        if (ti.isSelected())
                            checkItem = CheckItem.SelectedAllItem;
                        else
                            checkItem = checkItem.UnSelectedAllItem;
                    }
                }
            }
        } else {
            if (cbx.isChecked())
                checkItem = CheckItem.SelectedPageItem;
            else
                checkItem = checkItem.UnSelectedPageItem;
            checkPage = showPaging.getActivePage() + 1;
            List<Listitem> data = new ArrayList<>(sources.getItems());
            for (Listitem treeitem : data) {
                treeitem.setSelected(cbx.isChecked());
            }
        }
    }

    //导出
    protected void export(Component btn) {
        if (targets.getItems().isEmpty()) {
            WebUtils.showError(Labels.getLabel("editor.export.empty"));
            return;
        }
        if (Strings.isBlank(comment.getValue())) {
            WebUtils.notEmpty(Labels.getLabel("editor.export.comment"));
            return;
        }
        Clients.clearWrongValue(btn);
        //打包保存
        //生成所有的参数
        List<String> taskIdList = new ArrayList<>();
        for (Listitem li : targets.getItems()) {
            TypeLinkVo e = li.getValue();
            taskIdList.add(e.getEntityId());
        }
        List<LinkVo> entityLinkList = StudioApp.execute(new GetLinkCmd(taskIdList, true));
        //生成参数对应版本
        List<String> entityIdList = new ArrayList<>();
        for (LinkVo linkVo: entityLinkList) {
            entityIdList.add(linkVo.getEntityId());
            List<LinkVo> linkVos = StudioApp.execute(new GetLinkCmd(linkVo.getEntityId(), true));
            if (linkVos != null && linkVos.size() > 0) {
                for (LinkVo otherVo: linkVos) {
                    if (entityIdList.contains(otherVo.getEntityId()) == false) {
                        entityIdList.add(otherVo.getEntityId());
                    }
                }
            }
        }
        List<EntityInfo> entityList = StudioApp.execute(new GetEntryListCmd(entityIdList));
        System.out.println(entityList);
        //设置版本区间
        int max = 0;
        int min = 1000000000;
        for (EntityInfo e : entityList) {
            if (e.getVersion() > max)
                max = e.getVersion();
            if (e.getVersion() < min)
                min = e.getVersion();
        }
        StudioUtil.export(btn, entityList, comment.getValue(), min, max);
    }
}
